package com.zh.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.zh.springcloud.handler.MyBlockHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @Description:
 * @ClassName SentinelController
 * @date: 2021.07.21 22:04
 * @Author: zhanghang
 */
@RestController
public class SentinelController {

	@GetMapping("/testA")
	@SentinelResource(value = "testA")
	public String testA(){
		System.out.println(new Date() + Thread.currentThread().getName()+" \t  testA");
		return Thread.currentThread().getName()+"=====testA";
	}

	@GetMapping("/testB")
	public String testB(){
		return "=====testB";
	}

	@GetMapping("/testD")
	public String testD(@RequestParam Integer id){
		System.out.println(new Date() +  Thread.currentThread().getName()+" \t testD");
		if (id % 2 == 0){
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return "===testD"+id;
	}

	@GetMapping("/testHotKey")
	// /testHotKey 代表rest地址，testHotKey 代表资源名，要唯一
	@SentinelResource(value = "testHotKey",blockHandler = "deal_testHotKey")
	public String testHotKey(@RequestParam(value = "p1",required = false) String p1,@RequestParam(value = "p2",required = false) String p2){
		return " test 测试 -》 testHotKey"+ "p1 ->"+p1+",p2 ->" +p2;
	}

	public String deal_testHotKey(String p1, String p2, BlockException exception){
		// sentinel 系统的默认提示： Blocked by Sentintel (flow limiting)
		// 这里等于是指定了/testHotKey 接口的默认提示
		return " test 测试 -》 deal_testHotKey"+ "p1 ->"+p1+",p2 ->" +p2;
	}

	@GetMapping("/globalBlockHandler")
	// /testHotKey 代表rest地址，testHotKey 代表资源名，要唯一
	@SentinelResource(value = "testHotKey",  // 指定资源名
			blockHandlerClass = MyBlockHandler.class,  // 指定兜底方法的类
			blockHandler = "blockMethod")  // 指定兜底方法
	public String globalBlockHandler(){
		return " test 测试 -》 globalBlockHandler";
	}
}
